package com.hmall.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.hmall.common.dto.ItemPageQueryDTO;
import com.hmall.common.dto.PageDTO;
import com.hmall.common.pojo.Item;
import com.hmall.search.pojo.ItemDoc;
import com.hmall.search.service.SearchService;
import org.apache.commons.lang.StringUtils;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.lucene.search.function.CombineFunction;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder;
import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.MultiBucketsAggregation;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.elasticsearch.search.suggest.Suggest;
import org.elasticsearch.search.suggest.SuggestBuilder;
import org.elasticsearch.search.suggest.SuggestBuilders;
import org.elasticsearch.search.suggest.completion.CompletionSuggestion;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class SearchServiceImpl implements SearchService {

    private static final String HMALL = "hmall";
    @Autowired
    private RestHighLevelClient restHighLevelClient;

    /**
     * 基本搜索功能
     *
     * @param itemPageQueryDTO
     * @return {@link PageDTO}<{@link Item}>
     */
    @Override
    public PageDTO<ItemDoc> list(ItemPageQueryDTO itemPageQueryDTO) {
        try {
            //todo 1.准备request对象
            SearchRequest searchRequest = new SearchRequest(HMALL);
            String key = itemPageQueryDTO.getKey();
            int from = (itemPageQueryDTO.getPage() - 1) * itemPageQueryDTO.getSize();
            BoolQueryBuilder boolQueryBuilder = getBoolQueryBuilder(itemPageQueryDTO, key);
            //searchRequest.source().query(boolQueryBuilder);
            //todo 广告 -- 加分函数
            searchRequest.source().query(
                    QueryBuilders.functionScoreQuery(
                                    boolQueryBuilder,
                                    new FunctionScoreQueryBuilder.FilterFunctionBuilder[]{
                                            new FunctionScoreQueryBuilder.FilterFunctionBuilder(
                                                    QueryBuilders.termQuery("isAD",true),
                                                    ScoreFunctionBuilders.weightFactorFunction(100)
                                            )
                                    }
                            )
                            .boostMode(CombineFunction.SUM)
            );
            //todo 高亮
            searchRequest.source().highlighter(new HighlightBuilder().field("name").requireFieldMatch(false));
            //todo 3.排序
            if (itemPageQueryDTO.getSortBy().equals("sold")) {
                searchRequest.source().sort("sold", SortOrder.DESC);
            } else if (itemPageQueryDTO.getSortBy().equals("price")) {
                searchRequest.source().sort("price", SortOrder.ASC);
            }
            /*else {
                searchRequest.source()
                        .sort("price", SortOrder.ASC)
                        .sort("sold", SortOrder.DESC);

            }*/
            //todo 4.准备分页
            searchRequest.source().from(from).size(itemPageQueryDTO.getSize());
            //3.发送请求
            SearchResponse response = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
            //todo 4.解析响应
            PageDTO<ItemDoc> itemPageDTO = new PageDTO<>();

            SearchHits hits = response.getHits();
            //解析获取总数
            long total = hits.getTotalHits().value;
            SearchHit[] hitsHits = hits.getHits();
            List<ItemDoc> itemDocList = new ArrayList<>();
            for (SearchHit hit : hitsHits) {
                String sourceAsString = hit.getSourceAsString();
                ItemDoc itemDoc = JSON.parseObject(sourceAsString, ItemDoc.class);
                //高亮name解析
                Map<String, HighlightField> highlightFields = hit.getHighlightFields();
                if (!CollectionUtils.isEmpty(highlightFields)) {
                    HighlightField highlightField = highlightFields.get("name");
                    if (highlightField != null) {
                        String name = highlightField.getFragments()[0].string();
                        itemDoc.setName(name);
                    }
                }
                itemDocList.add(itemDoc);
            }
            itemPageDTO.setTotal(total);
            itemPageDTO.setList(itemDocList);
            return itemPageDTO;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 条件过滤 (抽取)
     *
     * @param itemPageQueryDTO
     * @param key
     * @return {@link BoolQueryBuilder}
     */
    private BoolQueryBuilder getBoolQueryBuilder(ItemPageQueryDTO itemPageQueryDTO, String key) {
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        //todo 2.1 关键字搜索  --准备query查询 --
        if (StringUtils.isEmpty(key)) {
            boolQueryBuilder.must(QueryBuilders.matchAllQuery());
        } else {
            boolQueryBuilder.must(QueryBuilders.matchQuery("all", key));
        }
        //todo. 2.2 分类,品牌,价格过滤
        //分类
        if (StringUtils.isNotEmpty(itemPageQueryDTO.getCategory())) {
            boolQueryBuilder
                    .filter(
                            QueryBuilders.termQuery("category", itemPageQueryDTO.getCategory())
                    );
        }
        //品牌
        if (StringUtils.isNotEmpty(itemPageQueryDTO.getBrand())) {
            boolQueryBuilder
                    .filter(
                            QueryBuilders.matchQuery("brand", itemPageQueryDTO.getBrand())
                    );
        }
        //价格
        if (Objects.nonNull(itemPageQueryDTO.getMinPrice()) && Objects.nonNull(itemPageQueryDTO.getMaxPrice())) {
            boolQueryBuilder.filter(
                    QueryBuilders.rangeQuery("price")
                            .gte(itemPageQueryDTO.getMinPrice())
                            .lte(itemPageQueryDTO.getMaxPrice())
            );
        }
        return boolQueryBuilder;
    }

    /**
     * 过滤项聚合功能
     *
     * @param itemPageQueryDTO
     * @return {@link Map}<{@link String}, {@link List}<{@link String}>>
     */
    @Override
    public Map<String, List<String>> filters(ItemPageQueryDTO itemPageQueryDTO) {
        try {
            //todo 1.给聚合添加范围查询 --- 分类、品牌、价格
            SearchRequest searchRequest = new SearchRequest(HMALL);
            searchRequest.source().size(0);
            BoolQueryBuilder boolQueryBuilder = getBoolQueryBuilder(itemPageQueryDTO, itemPageQueryDTO.getKey());
            searchRequest.source().query(boolQueryBuilder);
            //todo 2.多条件聚合 --- 分类和品牌
            String brandAgg = "brandAgg";
            searchRequest.source()
                    .aggregation(
                            AggregationBuilders.terms(brandAgg)
                                    .field("brand")
                                    .size(20)
                    );
            String categoryAgg = "categoryAgg";
            searchRequest.source().aggregation(
                    AggregationBuilders.terms(categoryAgg)
                            .field("category")
                            .size(20)
            );

            // todo 3.发送请求
            SearchResponse response = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);

            //todo 4.解析结果,返回
            Map<String, List<String>> map = new HashMap<>();
            Aggregations aggregations = response.getAggregations();

            Terms aggregationBrand = aggregations.get(brandAgg);
            Terms aggregationCategory = aggregations.get(categoryAgg);

            List<? extends Terms.Bucket> bucketsBrand = aggregationBrand.getBuckets();
            List<? extends Terms.Bucket> bucketsCategory = aggregationCategory.getBuckets();

            List<String> brandList = bucketsBrand.stream().map(MultiBucketsAggregation.Bucket::getKeyAsString)
                    .collect(Collectors.toList());
            List<String> categoryList = bucketsCategory.stream().map(MultiBucketsAggregation.Bucket::getKeyAsString)
                    .collect(Collectors.toList());

            map.put("category", categoryList);
            map.put("brand", brandList);

            return map;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 搜索栏自动补全功能 对品牌和分类进行拼音补全
     *
     * @param key
     * @return {@link List}<{@link String}>
     */
    @Override
    public List<String> suggestion(String key) {
        try {
            SearchRequest searchRequest = new SearchRequest(HMALL);

            String suggestionSuggest = "suggestionSuggest";
            searchRequest.source()
                    .suggest(
                            new SuggestBuilder()
                                    .addSuggestion(
                                            suggestionSuggest,
                                            SuggestBuilders.completionSuggestion("suggestion")
                                                    .prefix(key)
                                                    .skipDuplicates(true)
                                                    .size(10)
                                    )
                    );
            SearchResponse response = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
            //解析结果
            Suggest suggest = response.getSuggest();

            CompletionSuggestion completionSuggestion = suggest.getSuggestion(suggestionSuggest);
            List<CompletionSuggestion.Entry.Option> options = completionSuggestion.getOptions();
            List<String> suggestList = options.stream().map(option -> {
                return option.getText().string();
            }).collect(Collectors.toList());
            return suggestList;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
